from pms.common.views import PostFormula
from technology.models import Technology
from django.db.models.deletion import ProtectedError
from technology.models import Use


class API(PostFormula):

    require_permissions = [11]

    def handle(self, req):
        try:
            tid = req['id']
            tech = Technology.objects.get(id=tid)
            dtid = tech.id
            tech.delete()
            return self.success_respond({
                'id': dtid
            })
        except ProtectedError as e:  # 可能被[R5-使用]保护，也可能被[R10-掌握]保护
            protected_object = e.protected_objects.pop()
            if isinstance(protected_object, Use):
                return self.failed_respond('USE_TID_PROTECT', '该技术被[{}]{}项目使用，故不能删除'
                                           .format(protected_object.pid.id, protected_object.pid.name))
